package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.base.StringUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyJiKeYouQian;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeJiKeYouQian;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Map;

/**
 * 安心分期-V2吉客有钱 api分佣
 *
 * @author 江小游
 */
@ApiPlan(productId = "294", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatJiKeYouQianPhoneMd5Convert implements ApiPlatformPhoneMd5ConvertHandler {
    private static final String CHANNEL_CODE = "DL_ANXINFENQI";
    private static final String SECRET_KEY = "efa924eea8774e5a87ab56d1f40de11b";
    private static final String IV = "dxjf18129979469s";
    private static final String MERCHANT_NO = "TEST0001";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataChangeMessage) throws Exception {

        ApiPlatDataExchangeJiKeYouQian apiPlatDataExchange = new ApiPlatDataExchangeJiKeYouQian();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataChangeMessage);
        // 姓名Md5
        if (!StringUtils.isEmpty(apiDataChangeMessage.getUserName())){
            apiPlatDataExchange.setNameMd5(MD5.create().digestToHex(apiDataChangeMessage.getUserName()));
        }
        //手机号Md5
        apiPlatDataExchange.setPhoneMd5(apiDataChangeMessage.getPhoneMd5());
        //城市
        apiPlatDataExchange.setCityName(apiDataChangeMessage.getCity());
        //性別
        String sex = ChooseEq.create(apiDataChangeMessage.getSex())
                .when("0", "1")
                .when("1", "0")
                .end("0");
        apiPlatDataExchange.setSex(sex);
        apiPlatDataExchange.setAge(apiFieldConverter.getAgeInt());
        /*
       贷款金额
       0-3万：1
       3-5万：2
       5-10万：3
       10-20万：4
       20万以上：5
         */
        String loanAmount = ChooseEq.create(apiDataChangeMessage.getLoanAmount())
                .when("1", "1")
                .when("2", "3")
                .when("3", "4")
                .when("4", "5")
                .end("1");
        apiPlatDataExchange.setLoanAmount(loanAmount);
        /*
        职业
        自有职业：1
        上班族：2
        个体户：3
        企业主：4
         */
        String career = ChooseEq.create(apiDataChangeMessage.getCareer())
                .when("1", "2")
                .when("2", "1")
                .when("3", "4")
                .when("4", "2")
                .when("5", "3")
                .end("1");
        apiPlatDataExchange.setProfession(career);
       /*
          工资发放形式/银行代发/打卡方式
          现金收入：1
          打卡工资：2
        */
        String salaryPayMethod = ChooseEq.create(apiDataChangeMessage.getSalaryPayMethod())
                .when("1", "2")
                .when("2", "1")
                .when("3", "2")
                .end("1");
        apiPlatDataExchange.setSalaryType(salaryPayMethod);
        /*
        社保缴纳
        无：0
        6个月以下：1
        6个月以上：2
        */
        String socialSecurity = ChooseEq.create(apiDataChangeMessage.getSocialSecurity())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatDataExchange.setSocialSecurity(socialSecurity);
        /*
        公积金
        无：0
        6个月以下：1
        6个月以上：2
        */
        String providentFund = ChooseEq.create(apiDataChangeMessage.getProvidentFund())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatDataExchange.setProvidentFund(providentFund);
        /*
        车辆情况
        无车：0
        有按揭车：1
        有全款车：2
         */
        String carInfo = ChooseEq.create(apiDataChangeMessage.getCarInfo())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatDataExchange.setCar(carInfo);
        /*
        房产情况
        无房产: 0
        有按揭房产: 1
        有全款房产" 2
        */
        String realEstateInfo = ChooseEq.create(apiDataChangeMessage.getRealEstateInfo())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .when("6", "2")
                .end("0");
        apiPlatDataExchange.setEstate(realEstateInfo);
        /*
          信用卡额度
          无信用卡：0
        3000元以下：1
        3000-5000元:2
        5000-10000元:3
        10000元以上：4
        */
        String creditLimit = ChooseEq.create(apiDataChangeMessage.getCreditLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "3")
                .when("4", "4")
                .when("5", "4")
                .when("6", "1")
                .end("0");
        apiPlatDataExchange.setCreditCardLimit(creditLimit);
        /*
        我方字典-芝麻分
        无芝麻分：0
        650分以下：1
        650-700分：2
        700分以上：3
        */
        String sesameCredit = ChooseEq.create(apiDataChangeMessage.getSesameCredit())
                .when("1", "1")
                .when("2", "1")
                .when("3", "2")
                .when("4", "3")
                .end("0");
        apiPlatDataExchange.setZhiMaScore(sesameCredit);
        String insurancePolicy = ChooseEq.create(apiDataChangeMessage.getInsurancePolicy())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .end("0");
        apiPlatDataExchange.setLifeInsurance(insurancePolicy);
        /*
        月收入
        单位 元（整数型数字）
        */
        String monthlySalary = ChooseEq.create()
                .when(apiDataChangeMessage.getMonthlySalary(), "1", "3000")
                .when(apiDataChangeMessage.getMonthlySalary(), "2", "8000")
                .when(apiDataChangeMessage.getMonthlySalary(), "3", "15000")
                .when(apiDataChangeMessage.getMonthlySalary(), "4", "30000")
                .when(apiDataChangeMessage.getMonthlySalary(), "5", "50000")
                .end("5000");
        apiPlatDataExchange.setMonthIncome(monthlySalary);
        /*
        借款用途
        日常消费：1
        装修:2
        旅游:3
        教育培训:4
        婚庆:5
        */
        String loanPurpose = ChooseEq.create(apiDataChangeMessage.getLoanPurpose())
                .when("1", "3")
                .when("2", "4")
                .when("3", "5")
                .when("4", "2")
                .when("5", "1")
                .when("6", "1")
                .end("1");
        apiPlatDataExchange.setLoanPurpose(loanPurpose);
        /*
        借款
        一年以内：01
        1-3年：02
        3年上：03
       */
        String term = ChooseEq.create(apiDataChangeMessage.getLoanTerm())
                .when("1", "01")
                .when("2", "01")
                .when("3", "01")
                .when("4", "02")
                .when("5", "03")
                .when("6", "03")
                .end("01");
        apiPlatDataExchange.setLoanTerm(term);
        /*
        学历
        高中及以下：1
        大专：2
        本科及以上：3
        */
        String educationAttainment = ChooseEq.create(apiDataChangeMessage.getEducationAttainment())
                .when("1", "1")
                .when("2", "1")
                .when("3", "1")
                .when("4", "2")
                .when("5", "3")
                .when("6", "3")
                .end("1");
        apiPlatDataExchange.setDegree(educationAttainment);
        AES aes = AES.createCbc(SECRET_KEY.getBytes(), IV.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatDataExchange));
        return MapUtils.<String, Object>newHashMap(newMap -> {
            newMap.put("merchantNo", MERCHANT_NO);
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("timestamp", getTime(System.currentTimeMillis()));
            newMap.put("reqId", apiDataChangeMessage.getReqId());
            newMap.put("data", dataStr);
        });
    }

    public static String getTime(Long timestamp) {
        // 转换为 LocalDateTime
        LocalDateTime dateTime = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(timestamp),
                ZoneId.systemDefault()
        );
        // 定义格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化输出
        return dateTime.format(formatter);
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyMessage) throws Exception {
        //进件流程-默认JSON发送如果需要别的方式，或者需要增加请求头，请看apiApplyMessage拓展方法
        ApiPlatApplyJiKeYouQian apiPlatApply = new ApiPlatApplyJiKeYouQian();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyMessage);
        //赋值进件属性
        apiPlatApply.setCheckNo(apiApplyMessage.dataExchangeApplyId());
        // 姓名
        apiPlatApply.setName(apiApplyMessage.getUserName());
        // 手机号
        apiPlatApply.setPhone(apiApplyMessage.getPhone());
        // 年龄
        apiPlatApply.setAge(apiFieldConverter.getAgeInt());
        // 城市
        apiPlatApply.setCityName(apiApplyMessage.getCity());
        // 性別
        String sex = ChooseEq.create(apiApplyMessage.getSex())
                .when("0", "1")
                .when("1", "0")
                .end("0");
        apiPlatApply.setSex(sex);
        /*
        贷款金额
        0-3万：1
        3-5万：2
        5-10万：3
        10-20万：4
        20万以上：5
         */
        String loanAmount = ChooseEq.create(apiApplyMessage.getLoanAmount())
                .when("1", "1")
                .when("2", "3")
                .when("3", "4")
                .when("4", "5")
                .end("1");
        apiPlatApply.setLoanAmount(loanAmount);
        /*
        职业
        自有职业：1
        上班族：2
        个体户：3
        企业主：4
        */
        String career = ChooseEq.create(apiApplyMessage.getCareer())
                .when("1", "2")
                .when("2", "1")
                .when("3", "4")
                .when("4", "2")
                .when("5", "3")
                .end("1");
        apiPlatApply.setProfession(career);
       /*
       工资发放形式/银行代发/打卡方式
       现金收入：1
       打卡工资：2
        */
        String salaryPayMethod = ChooseEq.create(apiApplyMessage.getSalaryPayMethod())
                .when("1", "2")
                .when("2", "1")
                .when("3", "2")
                .end("1");
        apiPlatApply.setSalaryType(salaryPayMethod);
        /*
        社保缴纳
        无：0
        6个月以下：1
        6个月以上：2
        */
        String socialSecurity = ChooseEq.create(apiApplyMessage.getSocialSecurity())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatApply.setSocialSecurity(socialSecurity);
        /*
        公积金
        无：0
        6个月以下：1
        6个月以上：2
        */
        String providentFund = ChooseEq.create(apiApplyMessage.getProvidentFund())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatApply.setProvidentFund(providentFund);
        /*
        车辆情况
        无车：0
        有按揭车：1
        有全款车：2
         */
        String carInfo = ChooseEq.create(apiApplyMessage.getCarInfo())
                .when("1", "0")
                .when("2", "1")
                .when("3", "2")
                .when("4", "1")
                .end("0");
        apiPlatApply.setCar(carInfo);
        /*
        房产情况
        无房产: 0
        有按揭房产: 1
        有全款房产" 2

        3.*/
        String realEstateInfo = ChooseEq.create(apiApplyMessage.getRealEstateInfo())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .when("5", "1")
                .when("6", "2")
                .end("0");
        apiPlatApply.setEstate(realEstateInfo);
        /*
        信用卡额度
        无信用卡：0
        3000元以下：1
        3000-5000元:2
        5000-10000元:3
        10000元以上：4
        */
        String creditLimit = ChooseEq.create(apiApplyMessage.getCreditLimit())
                .when("1", "0")
                .when("2", "1")
                .when("3", "3")
                .when("4", "4")
                .when("5", "4")
                .when("6", "1")
                .end("0");
        apiPlatApply.setCreditCardLimit(creditLimit);
        /*
        芝麻分
        无芝麻分：0
        650分以下：1
        650-700分：2
        700分以上：3
         */
        String sesameCredit = ChooseEq.create(apiApplyMessage.getSesameCredit())
                .when("1", "1")
                .when("2", "1")
                .when("3", "2")
                .when("4", "3")
                .end("0");
        apiPlatApply.setZhiMaScore(sesameCredit);
        String insurancePolicy = ChooseEq.create(apiApplyMessage.getInsurancePolicy())
                .when("1", "0")
                .when("2", "1")
                .when("3", "1")
                .when("4", "1")
                .end("0");
        apiPlatApply.setLifeInsurance(insurancePolicy);
        /*
        月收入
        单位 元（整数型数字）
        */
        String monthlySalary = ChooseEq.create()
                .when(apiApplyMessage.getMonthlySalary(), "1", "3000")
                .when(apiApplyMessage.getMonthlySalary(), "2", "8000")
                .when(apiApplyMessage.getMonthlySalary(), "3", "15000")
                .when(apiApplyMessage.getMonthlySalary(), "4", "30000")
                .when(apiApplyMessage.getMonthlySalary(), "5", "50000")
                .end("5000");
        apiPlatApply.setMonthIncome(monthlySalary);
        /*
        借款用途
        日常消费：1
        装修:2
        旅游:3
        教育培训:4
        婚庆:5
        */
        String loanPurpose = ChooseEq.create(apiApplyMessage.getLoanPurpose())
                .when("1", "3")
                .when("2", "4")
                .when("3", "5")
                .when("4", "1")
                .when("5", "1")
                .when("6", "1")
                .end("1");
        apiPlatApply.setLoanPurpose(loanPurpose);
        /*
        借款
         一年以内：01
         1-3年：02
         3年上：03
        */
        String term = ChooseEq.create(apiApplyMessage.getLoanTerm())
                .when("1", "01")
                .when("2", "01")
                .when("3", "01")
                .when("4", "02")
                .when("5", "03")
                .when("6", "03")
                .end("01");
        apiPlatApply.setLoanTerm(term);
        /*
        学历
        高中及以下：1
        大专：2
        本科及以上：3
        */
        String educationAttainment = ChooseEq.create(apiApplyMessage.getEducationAttainment())
                .when("1", "1")
                .when("2", "1")
                .when("3", "1")
                .when("4", "2")
                .when("5", "3")
                .when("6", "3")
                .end("1");
        apiPlatApply.setDegree(educationAttainment);



        ArrayList<ApiPlatApplyJiKeYouQian.Accessory> accessoryList = new ArrayList<>();
        ApiPlatApplyJiKeYouQian.Accessory accessory = new ApiPlatApplyJiKeYouQian.Accessory();
        accessory.setAccessoryUrl(H5DomainUrlUtils.createUserProtocolUrl(apiApplyMessage.getProductPlanId(), apiApplyMessage.getPhoneMd5()));
        accessory.setAccessoryType("ACCREDIT");
        accessory.setAccessoryFileType("HTML");
        accessoryList.add(accessory);
        apiPlatApply.setAccessoryList(accessoryList);

        AES aes = AES.createCbc(SECRET_KEY.getBytes(), IV.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatApply));
        return MapUtils.<String, Object>newHashMap(newMap -> {
            newMap.put("merchantNo", MERCHANT_NO);
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("timestamp", getTime(System.currentTimeMillis()));
            newMap.put("reqId", apiApplyMessage.getReqId());
            newMap.put("data", dataStr);
        });
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        //进件返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        //根据文档响应判断
        if (!Eq.object(JsonUtils.get(respJson).getInteger("code"), 0)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }

        JSONObject resData = JsonUtils.get(respJson).getJSONObject("data");
        if (!Eq.object(resData.getInteger("dealStatus"), 1)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        RespPlatformPhoneMd5Apply respPlatformPhoneMd5Apply = RespPlatformPhoneMd5Apply.ofSuc();
        respPlatformPhoneMd5Apply.setCallUrl(resData.getString("redirectUrl"));
        return respPlatformPhoneMd5Apply;
    }


    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {

        if (JsonUtils.get(respJson) == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(JsonUtils.get(respJson).getInteger("code"), 0)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        JSONObject resData = JsonUtils.get(respJson).getJSONObject("data");
        if (!Eq.object(resData.getInteger("dealStatus"), 1)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        BigDecimal price = resData.getBigDecimal("price");
        String checkNo = resData.getString("checkNo");
        String logo = resData.getString("logo");
        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();
        result.setPrice(price);
        result.setApplyId(checkNo);
        result.setLogoPath(logo);
        result.setProductName("吉客有钱");
        result.setDisplayName("吉客有钱");
        return result;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        JSONObject jsonObject = JsonUtils.get(requestVO.getBody());
        String reqId = jsonObject.getString("reqId");

        RespPlatformNoticeApply applyNotice = new RespPlatformNoticeApply();
        applyNotice.setApplyId(reqId);
        return applyNotice;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatusMessage) {
        boolean b = apiBizStatusMessage.hasBizSuc();
        if (b) {
            return MapUtils.newHashMap(newHashMap -> {
                newHashMap.put("code", 0);
                newHashMap.put("msg", "操作成功");
            });
        }
        return MapUtils.newHashMap(newHashMap -> {
            newHashMap.put("code", 500);
            newHashMap.put("msg", "操作失败");
        });
    }
}
